/*
 * Generated.java
 *
 * Created on 31 de octubre de 2007, 13:53
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package cx.v1.factura;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import mx.gob.sat.cfd._2.comprobante.Comprobante;
import mx.gob.sat.cfd._2.prefijo.NamespacePrefixMapperImpl;

public class FacturaElectronica {
    
    public FacturaElectronica() {
    }

    public void createFacturaElectronica(Comprobante comprobante, String facturaElectronica) throws Exception 
    {
        try
        {
            Marshaller objSerializacionComprobante = JAXBContext.newInstance("mx.gob.sat.cfd._2.comprobante:mx.gob.sat.donatarias").createMarshaller();
                        
            objSerializacionComprobante.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());
            objSerializacionComprobante.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.sat.gob.mx/cfd/2 " +
                                                                                     "http://www.sat.gob.mx/sitio_internet/cfd/2/cfdv2.xsd " +
                                                                                     "http://www.sat.gob.mx/donat " +
                                                                                     "http://www.sat.gob.mx/sitio_internet/cfd/donat/donat.xsd");

            objSerializacionComprobante.marshal(comprobante, new FileOutputStream(facturaElectronica));
        }
        catch(Exception ex)
        {
            if(ex instanceof FileNotFoundException) throw new Exception("Se present� un error al intentar grabar la Factura Electr�nica en la ruta especificada: " + ex.getMessage());
            else throw new Exception("Se present� un error al intentar leer los datos del objeto Comprobante: " + ex.getMessage());    
        }
    }
    
    public void generateFacturaElectronica(String facturaElectronica, String firmaDeCadenaOriginal) throws Exception
    {
        try
        {
            Unmarshaller desSerializacion = JAXBContext.newInstance("mx.gob.sat.cfd._2.comprobante:mx.gob.sat.donatarias").createUnmarshaller();
        
            Comprobante comprobante = (Comprobante) desSerializacion.unmarshal(new FileInputStream(facturaElectronica));
            
            Marshaller objSerializacionComprobante = JAXBContext.newInstance("mx.gob.sat.cfd._2.comprobante:mx.gob.sat.donatarias").createMarshaller();
            
            objSerializacionComprobante.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapperImpl());
            objSerializacionComprobante.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.sat.gob.mx/cfd/2 " +
                                                                                     "http://www.sat.gob.mx/sitio_internet/cfd/2/cfdv2.xsd " +
                                                                                     "http://www.sat.gob.mx/donat " +
                                                                                     "http://www.sat.gob.mx/sitio_internet/cfd/donat/donat.xsd");

            comprobante.setSello(firmaDeCadenaOriginal);
            
            objSerializacionComprobante.marshal(comprobante, new FileOutputStream(facturaElectronica));
        }
        catch(Exception ex)
        {
            if(ex instanceof FileNotFoundException){
                throw new Exception("Se present� un error al intentar cargar la Factura Electr�nica de la ruta especificada: " + ex.getMessage());
            }
            else{
                throw new Exception("Se present� un error al intentar cargar la firma a la Factura Electr�nica: " + ex.getMessage());
            }
        }
                
    }    
    
    public String getCadenaOriginal(String facturaElectronica, String archivoXSLT, String id)throws Exception
    {
        String cadenaOriginal = "";
        try
        {
            String fileTemp;
            
            if(id == null){
                fileTemp = "~" + new Date().getTime();
            }else{
                fileTemp = "~" + id;
            }
            
            File file = new File(fileTemp);
            
            OutputStream out = new FileOutputStream(file);
            
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer(new StreamSource(archivoXSLT));
            
            transformer.transform(new StreamSource(new FileInputStream(facturaElectronica)), new StreamResult(out));
            
            InputStream in = new FileInputStream(new File(fileTemp));
            InputStreamReader streamReader = new InputStreamReader(in);
            BufferedReader bufferedReader = new BufferedReader(streamReader);
            
            cadenaOriginal = bufferedReader.readLine();

            streamReader.close();
            in.close();
            out.close();
            
            File eliminarFileTemp = new File(fileTemp);
            eliminarFileTemp.delete();
            
            if(cadenaOriginal.equals("|||")) cadenaOriginal = null;
        }
        catch(Exception ex)
        {
            throw new Exception("Se present� un error al intentar leer el archivo temporal para extraer la cadena original: " + ex.getMessage());
        }
        return cadenaOriginal;
    }
} 